<?php
namespace app\klingai\controller;
use think\Controller;
use think\Db;
use app\model\KlingaiRecord as RecordModel;
use Firebase\JWT\JWT;


class Base extends Controller
{
    public $login_user = [];
    protected $noCheckToken = [];

    public function __construct(){
        parent::__construct();
        // 验证token
        $action = $this->request->action();
        if (!empty($this->noCheckToken)) {
            $noCheckToken = array_map('strtolower',$this->noCheckToken);
        }else{
            $noCheckToken = [];
        }

        
        if ( !in_array($action, $noCheckToken) ) {
            $header = request()->header();
            $authorization = $header['authorization'];
            if (empty($authorization)) {
                exception('Authorization is empty',1001);
            }
            $authorization = str_replace('Bearer ', '', $authorization);

            $token = Db::name('sk')->field('sk,utype,user_id,ram_id,status')->where('sk',$authorization)->find();
            if ( empty($token) || $token['status'] == 0 ) {
                exception('Authorization is expired',1004);
            }

            $balance = Db::name('user')->where('id',$token['user_id'])->value('klingai_balance');
            if ($balance <= 0) {
                exception('Account balance not enough',1102);
            }
            
            $this->login_user = $token;
        }
    }

    public function getRequestInfo(){
        $data = [
            'method'=>request()->method(),
            'path'=>request()->path(),
            'header'=>request()->header()
        ];

        return $data;
    }

    public function createToken(){
        $payload = [
            'iss' => config('config.klingai.ak'),
            'exp'=> time() + 1800,
            'nbf' => time() - 5
        ];
        $jwtToken = JWT::encode($payload, config('config.klingai.sk'), 'HS256');
        
        return $jwtToken;
    }

    public function commonAction($price = 0){
        $data = $this->getRequestInfo(); // 获取请求相关信息

        $api_url = config('config.klingai.host').'/'.$data['path'];
        if (strtolower($data['method']) == 'post') {
            $data_string = file_get_contents('php://input');
            $params = json_decode($data_string,true);

            $header = [
                'Content-Type:application/json'
            ];
        }else{
            $params = request()->param();
            $api_url .= '?'.my_build_query($params);
            $params = [];
            $header = [];
        }
        $token = $this->createToken();
        $header[] = 'Authorization:Bearer '.$token;
        $params = json_encode($params,JSON_UNESCAPED_UNICODE);
        
        $result = httpRequest($api_url,$params,$data['method'],$header);
        $apiRes = json_decode($result,true);

        // 调用记录
        $ulogin = $this->login_user;
        $save_data = [
            'user_id'=>$ulogin['user_id'],
            'utype'=>$ulogin['utype'],
            'ram_id'=>$ulogin['ram_id'],
            'status'=>$apiRes['code'] == '0' ? 1 : 0,
            'ctime'=>time(),
            'method'=>$data['method'],
            'path'=>$data['path'],
            'header'=>json_encode($data['header'],JSON_UNESCAPED_UNICODE),
            'api_url'=>$api_url,
            'api_header'=>json_encode($header,JSON_UNESCAPED_UNICODE),
            'api_result'=>$result,
            'params'=>$params,
            'price'=>$price
        ];
        if ($save_data['status'] == 1 && !empty($apiRes['data']['task_id'])) {
            $save_data['task_id'] = $apiRes['data']['task_id'];
        }
        RecordModel::insert($save_data);
        // 扣除用户额度
        if ($price > 0) {
            Db::name('user')->where('id',$ulogin['user_id'])->dec('klingai_balance',$price)->update();
        }
        

        return $result;
    }

}
